<template>
  <div v-loading="loading">
    <el-collapse-transition>
      <div v-show="!isShowDetail" class="app-main-content-box">
        <app-main-title title="点餐记录" />

        <!--filter区域-->
        <div class="filter-container">
          <el-form
            ref="filterForm"
            :model="filterForm"
            label-width="100px"
            size="small"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item
                  label="选择时间："
                  :rules="[{ required: true, message: '时间区间不能为空' }]"
                  prop="customParams_Date"
                >
                  <el-date-picker
                    v-model="filterForm.customParams_Date"
                    size="small"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    :default-time="['00:00:00', '23:59:59']"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单编号：">
                  <el-input
                    v-model="params.orderNo"
                    placeholder="请输入订单编号"
                    class="input-with-select"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="取餐号：">
                  <el-input
                    v-model="params.offlineNo"
                    placeholder="请输入取餐号"
                    class="input-with-select"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="支付方式：" prop="customParams_Date">
                  <el-select v-model="params.payment" placeholder="请选择支付方式">
                    <el-option :value="1" label="微信支付">微信支付</el-option>
                    <!-- <el-option :value="2" label="支付宝支付">支付宝支付</el-option> -->
                    <el-option :value="3" label="余额支付">余额支付</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单状态：" prop="customParams_Date">
                  <el-select v-model="params.status" placeholder="请选择订单状态">
                    <el-option :value="1002" label="待付款">待付款</el-option>
                    <el-option :value="3" label="已完成">已完成</el-option>
                    <el-option :value="1001" label="已取消">已取消</el-option>
                    <el-option :value="9" label="已退款">已退款</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="交易状态：" prop="customParams_Date">
                  <el-select v-model="params.payStatus" placeholder="请选择交易状态">
                    <el-option :value="0" label="待支付">待支付</el-option>
                    <el-option :value="2" label="支付成功">支付成功</el-option>
                    <el-option :value="4" label="已退款">已退款</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="门店：" prop="customParams_Date">
                  <el-select v-model="params.shopId" placeholder="请选择门店">
                    <el-option v-for="item in storeList" :key="item.shopId" :value="item.shopId" :label="item.name">{{ item.name }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="优惠类型：" prop="customParams_Date">
                  <el-select v-model="params.discountType" placeholder="请选择优惠类型">
                    <el-option :value="0" label="积分">积分</el-option>
                    <el-option :value="1" label="卡">卡</el-option>
                    <el-option :value="2" label="券">券</el-option>
                    <el-option :value="3" label="会员">会员</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用餐方式：" prop="customParams_Date">
                  <el-select v-model="params.orderType" placeholder="请选择用餐方式">
                    <el-option :value="1" label="堂食">堂食</el-option>
                    <el-option :value="2" label="打包">打包</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item class="filter-btn">
              <el-button
                type="primary"
                round
                @click="submitForm('filterForm')"
              >查 询</el-button>
              <el-button
                round
                @click="resetForm('filterForm')"
              >重 置</el-button>
              <!-- <el-button
                round
                @click="downExcel"
              >导 出</el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <!--内容表格区域-->
        <!--数据明细显示部分-->
        <!--<div class="orderList-data-content flexRBC">-->
        <!--<div class="content-item">-->
        <!--<h3>有效订单总数</h3>-->
        <!--<h2>456</h2>-->
        <!--<span>全部订单：500单</span>-->
        <!--<span>无效订单：44单</span>-->
        <!--</div>-->
        <!--<div class="content-item">-->
        <!--<h3>有效订单原价合计</h3>-->
        <!--<h2>50000</h2>-->
        <!--<span>全部订单：￥55705</span>-->
        <!--<span>无效订单：￥5705</span>-->
        <!--</div>-->
        <!--<div class="content-item">-->
        <!--<h3>有效订单优惠金额</h3>-->
        <!--<h2>5000</h2>-->
        <!--<span>全部订单：￥6805</span>-->
        <!--<span>无效订单：￥1805</span>-->
        <!--</div>-->
        <!--<div class="content-item">-->
        <!--<h3>有效订单金额</h3>-->
        <!--<h2>45000</h2>-->
        <!--<span>全部订单：￥48900</span>-->
        <!--<span>无效订单：￥3900</span>-->
        <!--</div>-->
        <!--</div>-->

        <!-- 统计卡片 start -->
        <div>
          <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />
        </div>
        <!-- 统计卡片 end -->
        <div>
          <!-- 表格内容 -->
          <div class="list-table">
            <el-table
              size="small"
              :data="list"
              border
              stripe
              style="width: 100%"
              empty-text="暂无数据"
            >
              <el-table-column prop="createTime" min-width="100" label="下单时间" />
              <!-- <el-table-column prop="orderNo" label="订单号" /> -->
              <el-table-column label="订单号" min-width="130">
                <template slot-scope="scope">
                  <div class="btn_order" @click="openDetail(scope.row)">
                    {{ scope.row.orderNo }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="orderType" label="用餐方式" />
              <el-table-column prop="orderStatus" label="订单状态">
                <template slot-scope="scope">{{ orderStatusOptions[scope.row.orderStatus] }}</template>
              </el-table-column>
              <el-table-column prop="orderStatus" label="交易状态">
                <template slot-scope="scope">{{
                  tranOptions[scope.row.payStatus]
                }}</template>
              </el-table-column>
              <!-- <el-table-column prop="phone" label="预留手机" /> -->
              <el-table-column prop="offlineNo" label="取餐号" />
              <el-table-column prop="tableNo" label="桌台号" />
              <!-- <el-table-column prop="items" label="商品">
                <template slot-scope="scope">
                  <div v-for="(item, index) in scope.row.items" :key="index">
                    {{ item.itemName + " x " + item.count }}
                  </div>
                </template>
              </el-table-column> -->
              <el-table-column prop="shopInfo.shopName" label="门店" min-width="120" />
              <el-table-column prop="payment" label="支付方式" />
              <el-table-column prop="totalFee" label="订单金额" />
              <el-table-column prop="payFee" label="实收金额" />
              <el-table-column prop="discountType" label="优惠类型">
                <template slot-scope="scope">
                  {{ discountOptions[scope.row.discountType]||'--' }}
                </template>
              </el-table-column>
              <el-table-column prop="discountFee" label="订单优惠" />

              <!-- <el-table-column prop="totalFee" label="订单原价/元" />
              <el-table-column prop="discountFee" label="优惠金额/元" />
              <el-table-column prop="payFee" label="订单金额/元" /> -->
              <el-table-column label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    round
                    @click="openOrderDetail(scope.row)"
                  >详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination-direction
              v-if="paginationConfig.total !== 0"
              :config="paginationConfig"
              @sizeschange="sizesChange"
              @pagechange="pageChange"
            />
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <el-dialog title="商品信息" :visible.sync="showDetail">
      <ul class="pro_list">
        <li v-for="(item, index) in selectedItems" :key="index" class="pro_list_li">
          <div class="content">
            <div class="_img"><img :src="fileBaseUrl+item.productImg" alt="暂无图片"></div>
            <div class="right">
              <div class="_title">{{ item.productName }}</div>
              <div class="_class">规格：{{ item.productSpec.split(',').join('/') }}</div>
              <div class="_class">价格/数量：￥{{ (item.price / 100).toFixed(2) }} x {{ item.num }}</div>
            </div>
          </div>
          <div v-if="Object.keys(selectedList).toString().indexOf(item.productId)!=-1" class="_free">
            <span>赠</span>{{ returnSrting(selectedList[item.productId]) }}
          </div>
        </li>
      </ul>
    </el-dialog>
    <!-- 入账详情 -->
    <el-collapse-transition>
      <order-detail v-show="isShowDetail" ref="orderDetail" />
    </el-collapse-transition>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { downExportBookingOrders } from '@/api/download'
import { storeList } from '@/views/wxaMallModule/api/shop'
import { getOrderRecord, getOrderCount, getSnapshot } from '../../api/record'
import OrderDetail from '../components/OrderDetail'
export default {
  components: {
    OrderDetail
  },
  data() {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    return {
      // 配置
      // 分页配置
      testOptions: [2, 2, 1, 1, 1, 1, 2, 2, 2],
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      selectedItems: [],
      params: {
        beginTimestamp: start.getTime() / 1000,
        discountType: null, // 优惠类型
        endTimestamp: end.getTime() / 1000,
        offlineNo: null, // 取餐号
        orderNo: null, // 桌号
        orderType: null, // 订单类型 1 堂食 2打包
        pageNum: 1,
        pageSize: 10,
        payStatus: null, //支付状态
        payment: null, //支付类型
        shopId: null, //门店id
        status: null //订单状态

      },
      storeList: [],
      statusOptions: {
        1: '待支付',
        2: '待支付',
        3: '已完成',
        4: '已取消',
        5: '已取消',
        6: '已完成',
        7: '已完成',
        8: '已完成',
        9: '已退款'
      },
      tranOptions: {
        0: "待支付",
        2: "支付成功",
        4: "已退款",
        6:'-'
      },
      orderStatusOptions: {
        1: '待付款',
        2: '待付款',
        4: '已取消',
        5: '已取消',
        3: '已完成',
        9: '已退款'
      },
      discountOptions: {
        0: '积分优惠',
        1: '卡优惠',
        2: '券优惠',
        3: '会员优惠'
      },

      selectOptions: [
        {
          value: 'orderNo',
          label: '订单编号'
        },
        {
          value: 'offlineNo',
          label: '取餐号'
        }
      ],
      // 状态

      loading: false, // 表格loading
      isShowDetail: false,
      showDetail: false,
      // 数据
      statisticsCardData: [],
      searchSelect: 'orderNo', // 搜索的类型
      list: [], // 表格数据
      shopListOption: [], // 所有门店
      filterForm: {
        shopId: '',
        customParams_Date: [
          this.$momentMini(start).format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini(end).format('YYYY-MM-DD') + ' 23:59:59'
        ],
        offlineNo: '',
        orderNo: '',
        payment: '',
        status: ''
      },
      detailList: [],
      selectedList: ''
    }
  },
  computed: {
    ...mapGetters(['paymentOptions', 'fileBaseUrl']),
    msgGetOrderNo() {
      return this.$store.state.message.msgGetOrderNo
    }
  },
  watch: {
    msgGetOrderNo() {
      this.openMsgOrderInfo()
    },
    searchSelect(val) {
      this.filterForm.offlineNo = ''
      this.filterForm.orderNo = ''
    }
  },
  created() {
    this.getStoreList()
  },
  mounted() {
    // this.getList(this.params)
    this.fetchData()
    this.openMsgOrderInfo()
    const arrFrom = ['invoice','cancelTable']
    this.$route.query.orderNo && arrFrom.indexOf(this.$route.query.from) > -1 && this.openOrderDetail({ orderNo: this.$route.query.orderNo })
  },
  methods: {
    openMsgOrderInfo() {
      // 订单消息跳转过来后弹窗
      const { orderNo, path } = this.msgGetOrderNo
      const isCan = this.$route.path === path
      if (orderNo && isCan) {
        this.openOrderDetail({ orderNo })
        this.$store.dispatch('SetMsgOrderNo', {})
      }
    },
    /**
     * 获取数据
     */
    // 获取列表
    getStoreList() {
      storeList({}).then(res => {
        this.storeList = res.data
      })
    },
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize

    ) {
      this.$refs.filterForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.params.pageNum = page
          this.params.pageSize = pageSize
          this.params.beginTimestamp = new Date(this.filterForm.customParams_Date[0]).getTime() / 1000
          this.params.endTimestamp = new Date(this.filterForm.customParams_Date[1]).getTime() / 1000
          Promise.all([this.getList(this.params), this.getCount(this.params)]).then(
            (res) => {
              this.loading = false
            }
          )
        }
      });
    },

    // 获取筛选数据
    setRequestParams() {
      let params = {}
      params = Object.assign({}, this.filterForm)
      params.beginTimestamp = this.$momentMini(params.customParams_Date[0]).unix()
      params.endTimestamp = this.$momentMini(params.customParams_Date[1]).unix()
      delete params.customParams_Date
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      return params
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        getOrderRecord(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.pageNum !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '已完成订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            },
            {
              title: '已退款订单 / 元',
              value: 0,
              describeList: [],
              detailList: ['笔数：0', '优惠：￥0', '单均：￥0']
            }
          ]
          getOrderCount(params)
            .then((res) => {
              const indexObj = {
                3: 0,
                9: 1
              }
              res.data.forEach((v) => {
                switch (v.status) {
                  case 3:
                  case 9:
                    const index = indexObj[v.status]
                    this.statisticsCardData[index].value = v.tradeFee
                    this.statisticsCardData[index].detailList = [
                      `笔数：${v.num}`,
                      `优惠：￥${v.discount}`,
                      `单均：￥${(v.tradeFee / v.num).toFixed(2)}`
                    ]
                    break
                }
              })
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },
    returnSrting(arr) {
      let Str = ''
      arr.forEach((ele, index) => {
        Str += `${ele.productName}${ele.num}份${arr.length - 1 == index ? '' : ','}`
      })
      return Str
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },
    /**
     * 按钮组
     */
    // 导出
    downExcel() {},

    // 查询
    submitForm() {
      this.paginationConfig.page = 1
      this.fetchData()
    },

    // 重置
    resetForm() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.filterForm.customParams_Date = [
        this.$momentMini(start).format('YYYY-MM-DD') + ' 00:00:00',
        this.$momentMini(end).format('YYYY-MM-DD') + ' 23:59:59'
      ]
      this.params = {
        beginTimestamp: start.getTime() / 1000,
        discountType: null, // 优惠类型
        endTimestamp: end.getTime() / 1000,
        offlineNo: null, // 取餐号
        orderNo: null, // 桌号
        orderType: null, // 订单类型 1 堂食 2打包
        pageNum: 1,
        pageSize: 10,
        payStatus: null, //支付状态
        payment: null, //支付类型
        shopId: null, //门店id
        status: null //订单状态

      }
    },

    // 跳转详情
    openOrderDetail(row) {
      this.isShowDetail = true
      this.$refs.orderDetail.open({ orderNo: row.orderNo }).then((res) => {
        this.isShowDetail = false
        this.fetchData()
      })
    },
    openDetail(row) {
      getSnapshot({ orderId: row.orderId }).then(res => {
        console.log(res)
        this.selectedItems = res.data.cySellItemSnapshots
        this.selectedList = res.data.cyItemGiftSnapshotMap
        this.showDetail = true
      })

    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.filter-container {
  .el-select {
    // width: 120px;
    width: 100%;
  }
  .el-input {
    width: 100%;
    // width: 400px;
  }
  .el-range-editor {
    width: 100%;
  }
}
.filter-btn {
  margin-bottom: 20px;
}
// 单选换行
.el-radio + .el-radio {
  margin-left: 0;
}
.el-radio {
  margin-right: 10px;
  line-height: 32px;
}
.btn_order {
  &:hover {
    color: #ffb72f;
    cursor: pointer;
  }
}
.pro_list{
  max-height: 400px;
  overflow-y: scroll;
  &::-webkit-scrollbar{
    display: none;
    // width: 10px;
  }
  .pro_list_li{
    margin: 10px 0;
  .content{
    display: flex;
    align-items: center;
    ._img{
      width: 90px;
      height: 90px;
      background-color: #ffb72f;
      border-radius: 10px;
      overflow: hidden;
    }
    .right{
      display: flex;
      flex: 1;
      margin-left: 30px;
      justify-content: space-between;
    }
  }
  ._free{
    margin:20px 0 20px 120px;
    color: #d1d1d1;
    span{
      background: #ffb72f;
      color: #fff;
      font-size: 14px;
      display: inline-block;
      padding: 2px;
      margin-right: 20px;
    }
  }
}
}

</style>
